import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *



def print_with_time(*args, **kwargs):
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)















def On_InputPage_UploadSkuPicture_And_SetSkuName(driver:WebDriver,SkuName:str,Picture_Name:str=None,Delay:float=2):
    
    # 1.填写颜色
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./span[text()='请选择/输入颜色分类'] and .//input]//input")))
        element.send_keys(SkuName)
        
        try:
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[contains(@style,'position') and contains(@style,'absolute')]//li//span[text()='{SkuName}']")))
        except TimeoutException:
            print(f"提示 : 没有等待输入 [颜色] 后的结果!")
        
    except TimeoutException:
        print("提示 : 没有找到 [颜色] 的 [input] 控件!")
    
    
    try:
        # 实现 选择颜色的逻辑
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[contains(@style,'position') and contains(@style,'absolute')]//li//span[text()='{SkuName}']")))
        try:
            element.click()
            try:
                element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[contains(@style,'position') and contains(@style,'absolute')]//button/span[contains(text(),'确定')]")))
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
    except TimeoutException:
        print("提示 : 没有找到 [目标颜色] !")

    # 2.上传颜色图片
    # 
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@id='skuValue-颜色分类']/div[not(contains(@class,'skuValueInput')) and .//span[text()='{SkuName}']]//input[@type='file' and not(@multiple)]")))
        element.send_keys(pathlib.Path(Picture_Name).absolute().resolve().__str__())
        time.sleep(Delay)
        
        # 判断是否需要裁剪图片
        try:
            element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./div/*[text()='图片裁剪'] and .//span[text()='确定']]//span[text()='确定']")))
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            time.sleep(Delay)
        except TimeoutException:
            print("提示 : 没有找到 [图片裁剪] 按钮!")
            
    except TimeoutException:
        print(f"提示 : 没有找到 [{SkuName}] 对应的图片上传元素!")
    finally:
        time.sleep(Delay)